<template>
    <el-form-item label="封面" :prop="props.upInfo.prop">
        <el-upload
            ref="uploadRef"
            list-type="picture-card"
            accept=".jpg,.jpeg,.png,.gif,.bmp,.webp"
            :limit="1"
            :auto-upload="false"
            :on-exceed="handleExceed"
            :before-upload="beforeUpdata"
            :on-change="handleChange"
            :file-list="uploadFileList"
            :on-remove="Remove"
            :on-preview="dialogImageUrl"
            :class="{ hide: hideUpload }">
            <template #default>
                <el-icon class="upload_icon">
                    <plus />
                </el-icon>
            </template>
            <template #file="{ file }">
                <div>
                    <el-image :src="file.url"> </el-image>
                    <span class="el-upload-list__item-actions">
                        <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                            <el-icon><zoom-in /></el-icon>
                        </span>
                        <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                            <el-icon><delete /></el-icon>
                        </span>
                    </span>
                </div>
            </template>
            <template #tip>
                <div class="el-upload__tip">
                    <span>图片支持JPG、PNG、JPEG格式，大小2M以内。</span>
                </div>
            </template>
        </el-upload>
    </el-form-item>
    <el-dialog v-model="dialogVisible" class="pre_img_box">
        <el-image w-full :src="dialogImageUrl"> </el-image>
    </el-dialog>
</template>
<script setup lang="ts">
import { ref, defineProps, onUnmounted, computed } from 'vue';
import { ElMessage } from 'element-plus';
import type { UploadInstance } from 'element-plus';
import { Plus, ZoomIn, Delete } from '@element-plus/icons-vue';
import type { UploadFile } from 'element-plus/es/components/upload/src/upload';
import { uploadFile2 } from '@/api/common';
import { IsNotEmpty } from '@/utils/utils';
import bus from '@/utils/bus';
import { endLoading, startLoading } from '@/utils/request';
const emit = defineEmits(['submit']);

const uploadRef = ref<UploadInstance>();

const dialogImageUrl = ref('');
const dialogVisible = ref(false);
const disabled = ref(false);
const uploadFileList = ref([]);
const isEdit = ref(false); // 是否为编辑

const props = defineProps<{
    upInfo: {
        type: number; //文件类型
        label: string; //文件名称
        prop: string; // 是否是必传
        files: any; //文件
        multiple: {
            //是否支持多选
            type: boolean;
            default: false;
        };
        limitSize: number; // 最大文件上传限制
        limitNum: {
            // 上最大传数量
            type: number;
            default: 1;
        };
        acceptFile: string; // 上传类型文件判断
    };
}>();
const hideUpload = computed(() => {
    return uploadFileList.value.length >= (isEdit.value ? 1 : props.upInfo.limitNum);
});
const beforeUpdata = async (file: any, fileList: any[] = []) => {
    const is2M = file.size / 1024 / 1024 <= props.upInfo.limitSize;
    // const { W, H } = await getImage_wh(file)
    const ext = file.name.substring(file.name.lastIndexOf('.'));
    if (props.upInfo.acceptFile.indexOf(ext) == -1) {
        fileList = [];
        ElMessage.warning(`该图片是${ext}格式,请上传${props.upInfo.acceptFile}格式图片`);
        handleRemove(file);
        return;
    }
    // if (W > 1440) {
    //   ElMessage.warning(`该图片宽度${W}px,超过最大图片尺寸宽度1440px`)
    //   handleRemove(file)
    //   return
    // }
    // if (H > 1080) {
    //   ElMessage.warning(`该图片高度${H}px,超过最大图片尺寸高度1080px`)
    //   handleRemove(file)
    //   return
    // }
    if (!is2M) {
        fileList = [];
        ElMessage.warning(`上传的图片最大支持${props.upInfo.limitSize}M`);
        handleRemove(file);
        return;
    }
    // return is2M && W <= 1440 && H <= 1080
    return is2M;
};
const handleRemove = (file: UploadFile) => {
    uploadFileList.value.length = 0;
    uploadFileList.value = uploadFileList.value.filter((item: any) => item.url != file.url);
    emit('submit', uploadFileList.value);
};
const Remove = (file: UploadFile, list: UploadFile[]) => {
    uploadFileList.value.length = 0;
    uploadFileList.value = list;
    emit('submit', list);
    bus.emit('empty');
};
// 上传文件
const uploadImg = async (file: any) => {
    const flag = await beforeUpdata(file);
    if (!flag) return;
    startLoading();
    return await uploadFile2(
        {
            file,
            fileName: file.name
        },
        null,
        true
    );
};
// 上传改变
const handleChange = async (file: UploadFile, list: UploadFile[]) => {
    const existFile = list.slice(0, list.length - 1).find(f => f.name === file.name);
    if (existFile) {
        ElMessage.error('当前文件已经存在!');
        list.pop();
        return;
    }
    try {
        const res: any = await uploadImg(file.raw);
        if (IsNotEmpty(res)) {
            uploadFileList.value.push(res);
            emit('submit', uploadFileList.value);
        }
        endLoading();
    } catch (error) {
        endLoading();
    }
};
const handleExceed = (file: UploadFile, list: UploadFile[]) => {
    ElMessage.warning(
        `当前限制选择 ${props.upInfo.limitNum} 个文件，本次选择了 ${props.upInfo.files.length} 个文件，共选择了 ${
            props.upInfo.files.length + list.length
        } 个文件`
    );
    Remove(file, list);
};
const uploadRequest = async (params: any) => {
    try {
        const data: any = await uploadImg(params.file);
        uploadFileList.value.push(data);
        emit('submit', uploadFileList.value);
        endLoading();
    } catch (error) {
        endLoading();
    }
};
// 图片数据回显
const echo = (data: any) => {
    isEdit.value = true;
    if (props.upInfo.type == 1) {
        if (data.cover_image_url) {
            uploadFileList.value.push({ url: data.cover_image_url });
        } else {
            data.forEach((item: any) => {
                uploadFileList.value.push({ url: item.absolute_url });
            });
        }
    } else if (props.upInfo.type == 4) {
        uploadFileList.value.push({ name: data.title, url: undefined });
    }
    return;
};
// 清空数据回显
const empty = () => {
    uploadFileList.value = [];
};
// 编辑状态时只能上传一张照片
const singleImg = (res: boolean) => {
    isEdit.value = res;
};
//上传图片的弹框
const upPic = () => {
    isEdit.value = false;
};
bus.on('upPic', upPic);

// 主动暴露方法
defineExpose({ empty, echo, singleImg, upPic });
const handlePictureCardPreview = (file: UploadFile) => {
    dialogImageUrl.value = file.url!;
    dialogVisible.value = true;
};
// 下载
const handleDownload = (file: UploadFile) => {};
onUnmounted(() => {
    bus.off('upPic', upPic);
});
</script>
<style lang="scss" scoped>
.pre_img_box {
    overflow: hidden;

    .pre_image {
        display: block;
        margin: auto;
        max-height: 400px;
    }
}
</style>
<style>
.hide .el-upload--picture-card {
    display: none;
}

.upload_icon {
    width: 140px;
    height: 90px;
}

.el-upload__tip {
    font-size: 12px;
    color: #999;
}
</style>
